package com.jt.service;

import com.jt.vo.ImageVO;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.PropertySource;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import javax.imageio.ImageIO;
import java.awt.image.BufferedImage;
import java.io.File;
import java.io.IOException;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.UUID;

@Service
@PropertySource("classpath:/properties/image.properties")
public class FileServiceImpl implements FileService{

    //为属性动态赋值 注解@Value
    @Value("${image.localPathDir}")
    private String localPathDir;        // = "D:/JT_IMAGE";
    @Value("${image.localUrlPath}")
    private String localUrlPath;        // = "http://image.jt.com";

    //1.参数  ~~~~已知条件
    //2.干什么  ~~~~实现文件上传
    //3.返回值： void ImageVO  有效返回


    /**
     * 文件上传案例实现
     * 1.如何保证前端上传的数据是有效的
     *      1.1校验文件的名称检查是否为图片
     *      1.2校验是否为恶意程序
     * @param file
     * @return
     */
    @Override
    public ImageVO upload(MultipartFile file) throws IOException {
        //1.1校验是否为图片类型
        String fileName = file.getOriginalFilename();

        fileName = fileName.toLowerCase();

        if(!fileName.matches("^.+\\.(jpg|png|gif)$")){
            return null;
        }
        System.out.println("通过类型的校验");
        //1.2 校验图片类型是否为木马
        try{
            BufferedImage bufferedImage =ImageIO.read(file.getInputStream());
            int width = bufferedImage.getWidth();
            int height = bufferedImage.getHeight();
            if(width == 0 || height == 0){
                return null;
            }
        }catch (Exception e){
            return null;
        }
        //2.实现文件上传
        //2.1实现分目录存储。。。可以以时间维度进行分割  /yyyy/mm/dd/

        String datePath = new SimpleDateFormat("/yyyy/MM/dd/").format(new Date());

        //2.2 进行目录的拼接
        String localDir = localPathDir + datePath;
        //2.3需要创建目录
        File dirFile = new File(localDir);
        if(!dirFile.exists()){
            dirFile.mkdirs();
        }
        //3.文件名称重复问题  采用UUID防止文件重名
        
        String uuid = UUID.randomUUID().toString().replace("-", "");

        String fileType = fileName.substring(fileName.lastIndexOf("."));
        String realFileName = uuid + fileType;
        String filePathAll = localDir + realFileName;
        //实现文件上传
        File realFile = new File(filePathAll);
        file.transferTo(realFile);

        //2021/11/11/uuid.jpg
        String virtuaPath = datePath + realFileName;
        //http://image.jt.com/2021/11/11/uuid.jpg
        String urlPath =localUrlPath + virtuaPath;



        return new ImageVO(virtuaPath,urlPath,realFileName);
    }

    //如何实现文件删除filePathfilePath
    @Override
    public void fileRemove(String virtualPath) {
        String filePath = localPathDir + virtualPath;
        File file = new File(filePath);
        //删除文件
        file.delete();

    }
}
